group_by_first_letter.py
¶Define the key
Initialize the key (if necessary)
if key not in groups
, then initialize the key, often to an empty listAdd the item to the group
Group a sequence of words by their length.
Use an input loop. Print word groups at the end.
group_by_size.py
¶tuple
+ dict
¶data = {
('Monday', '1pm'): 'CS 110',
('Tuesday', '2pm'): 'CS 235',
('Wednesday', '1pm'): 'CS 110',
('Thursday', '2pm'): 'CS 235',
('Friday', '1pm'): 'CS 110'
}
data['Monday']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[3], line 1 ----> 1 data['Monday'] KeyError: 'Monday'
data['Monday', '1pm']
'CS 110'
You can use a tuple
as a key in a dictionary.
time = ['Monday', '1pm']
data[time]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[4], line 2 1 time = ['Monday', '1pm'] ----> 2 data[time] TypeError: unhashable type: 'list'
You can't use a list
or a dict
as a key in a dictionary.
If you see an "unhashable type" TypeError
, it's because you are trying to use something as a key that doesn't work as a key (list
and dict
are the more common offenders).
You'll learn what "unhashable" means in CS 235. 🙂
Group words based on their first and last letters.
Use an input loop. Print the groups at the end.
first_and_last.py
¶Define the key
Initialize the key (if necessary)
if key not in groups
, then initialize the key, often to an empty listAdd the item to the group